<template>
  <div class="app-container">
    <!-- 搜索框以及添加人员按钮 -->
    <div class="header">
      <el-form :model="searchParams" ref="queryForm" size="small" :inline="true" class="searchParams">
        <el-form-item label="登入账号" prop="searchAddress">
          <el-input v-model="searchParams.searchUserName" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="姓名" prop="searchAddress">
          <el-input v-model="searchParams.searchName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="角色" prop="searchRole">
          <el-input v-model="searchParams.searchRole" placeholder="请输入角色" clearable />
        </el-form-item>
      </el-form>
      <el-form :model="searchParams" ref="queryForm" size="small" :inline="true" class="searchParams">
        <el-form-item label="所属区域" prop="searchAddress">
          <el-input v-model="searchParams.searchAddress" placeholder="请输入所属区域" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="el-icon-circle-plus-outline" circle @click="addUserDialog = true" />
        </el-form-item>
      </el-form>
    </div>
    <!-- 页面数据 -->
    <div class="table">
      <el-table :data="tableData" height="500" border style="width: 100%" @row-click="handlerRow">
        <el-table-column prop="id" label="id" width="40"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="name" label="姓名"> </el-table-column>
        <el-table-column prop="phone" label="电话"> </el-table-column>
        <el-table-column prop="address" label="家庭地址"> </el-table-column>
        <el-table-column prop="town_name" label="所属区域"> </el-table-column>
        <el-table-column label="角色">
          <template slot-scope="scope">
            {{
              scope.row.role === 0
              ? "管理员"
              : scope.row.role === 1
                ? "老板"
                : scope.row.role === 2
                  ? "审批员"
                  : "员工"
            }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.stop="updateUser(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click.stop="delUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增用户dialog -->
    <el-dialog title="添加用户" :visible.sync="addUserDialog" style="margin-top: 5vh !important">
      <el-form :model="addUserForm" ref="addUserForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="账户" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="家庭地址" prop="address">
          <el-input v-model="addUserForm.address"></el-input>
        </el-form-item>
        <el-form-item label="所属区域" prop="town_id">
          <el-select v-model="addUserForm.town_id" placeholder="请选择所属区域">
            <el-option v-for="item in regionData" :key="item.id" :label="item.town_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addUserForm.role" placeholder="请选择用户角色">
            <el-option v-for="item in roleData" :key="item.id" :label="item.role" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 根据所属区域选择考勤组和审批组 -->
        <el-form-item label="所属审批组" prop="approver_id">
          <el-select v-model="addUserForm.approver_id" placeholder="请选择用户所属审批组">
            <el-option v-for="item in approverData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属考勤组" prop="attendance_id">
          <el-select v-model="addUserForm.attendance_id" placeholder="请选择用户所属考勤组">
            <el-option v-for="item in attendanceData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('add')">取 消</el-button>
        <el-button type="primary" @click="addUser('addUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户dialog -->
    <el-dialog title="修改用户" :visible.sync="updateUserDialog" style="margin-top: 5vh !important">
      <el-form  
      :model="updateUserForm"
        ref="updateUserForm"
        :rules="rules"
        label-width="100px"
        label-position="left">
        <el-form-item label="账户" prop="username">
          <el-input v-model="updateUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="updateUserForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="updateUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="updateUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="家庭地址" prop="address">
          <el-input v-model="updateUserForm.address"></el-input>
        </el-form-item>
        <el-form-item label="所属区域" prop="town_id">
          <el-select v-model="updateUserForm.town_id" placeholder="请选择所属区域">
            <el-option v-for="item in regionData" :key="item.id" :label="item.town_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="updateUserForm.role" placeholder="请选择用户角色">
            <el-option v-for="item in roleData" :key="item.id" :label="item.role" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 根据所属区域选择考勤组和审批组 -->
        <el-form-item label="所属审批组" prop="approver_id">
          <el-select v-model="updateUserForm.approver_id" placeholder="请选择用户所属审批组">
            <el-option v-for="item in approverData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属考勤组" prop="attendance_id">
          <el-select v-model="updateUserForm.attendance_id" placeholder="请选择用户所属考勤组">
            <el-option v-for="item in attendanceData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('update')">取 消</el-button>
        <el-button type="primary" @click="update('updateUserForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
    
<script>
import { getAccounts, searchData, addUser, updateUser,deleteUser} from "@/api/account";
import { getTown } from "@/api/town";
import { idToApprover } from "@/api/approver";
import { idToAttendance } from "@/api/attendance";
import { dateFormat } from "@/utils/utils";
export default {
  name:'userPage',
  data() {
    return {
      // 查询字段
      searchParams: {
        searchUserName: "",
        searchName: "",
        searchRole: "",
        searchAddress: "",
      },
      // 页面数据
      tableData: [],
      // 用户数据
      userData: [],
      // 区域信息
      regionData: [],
      // 角色信息
      roleData: [
        {
          id: 1,
          role: "老板",
        },
        {
          id: 2,
          role: "审批员",
        },
        {
          id: 3,
          role: "普通职员",
        },
      ],
      // 审批组信息
      approverData: [],
      // 考勤组信息
      attendanceData: [],
      //分页符
      number: 0,
      currentPage4: 1,
      table: [],
      size: 10,
      current: 1,
      addUserDialog: false,
      updateUserDialog: false,
      // 添加用户数据
      addUserForm: {
        username: null,
        password: null,
        name: null,
        phone: null,
        address: null,
        town_id: null,
        role: null,
        attendance_id: null,
        approver_id: null,
      },
      // 修改用户数据
      updateUserForm: {
        username: null,
        password: null,
        name: null,
        phone: null,
        address: null,
        town_id: null,
        role: null,
        attendance_id: null,
        approver_id: null,
      },
      // 验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户登入账号", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户登入密码", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入用户电话", trigger: "blur" }],
        address: [
          { required: true, message: "请输入用户家庭住址", trigger: "blur" },
        ],
        role: [{ required: true, message: "请选择用户职位", trigger: "blur" }],
        town_id: [
          { required: true, message: "请选择用户所属区域", trigger: "blur" },
        ],
        approver_id: [
          { required: true, message: "请选择用户所属审批组", trigger: "blur" },
        ],
        attendance_id: [
          { required: true, message: "请选择用户所属考勤组", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    "addUserForm.town_id": {
      handler(newVal, oldVal) {
        if (newVal !== oldVal && newVal !== null) {
          this.getApprover(newVal);
          this.getAttendance(newVal);
        }
      },
      // deep:true
    },
    "updateUserForm.town_id": {
      handler(newVal, oldVal) {
        if (newVal !== oldVal && newVal !== null) {
          this.getApprover(newVal);
          this.getAttendance(newVal);
        }
      },
    },
  },
  methods: {
    // 获取页面数据
    async getAccount() {
      // 获取用户信息
      await getAccounts().then((res) => {
        if (res.status === 0) {
          this.userData = res.data;
          this.userData.forEach(user=>{
            user.createTime = dateFormat(user.createDate)
          })
        }
      });
      // 获取所属区域信息
      await getTown().then((res) => {
        if (res.status === 0) {
          this.regionData = res.data;
        }
      });
      this.init();
    },
    // 初始化页面数据，
    init() {
      this.tableData = [];
      this.userData.forEach((item) => {
        this.regionData.forEach((card) => {
          if (item.town_id === card.id) {
            item.town_name = card.town_name;
            this.tableData.push(item);
          }
        });
      });
    },
    //查询功能
    handleQuery() {
      searchData(this.searchParams).then((res) => {
        if (res.status === 0) {
          this.userData = res.data;
          this.init();
        }
      });
    },
    //重置搜索框内容
    resetQuery() {
      this.searchParams = {
        searchUserName: "",
        searchName: "",
        searchDate: "",
        searchAddress: "",
      };
    },
    //添加用户
    addUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addUser(this.addUserForm).then((res) => {
            if(res.status === 0){
              this.$message.success('新增成功')
              this.getAccount();
              this.addUserDialog = false;
            }
            
          });
        } else {
          return false;
        }
      });
    },
    // 新增用户dialog取消按钮
    resetForm(data) {
      if (data === "add") {
        this.addUserForm = {
          username: null,
          password: null,
          name: null,
          phone: null,
          address: null,
          town_id: null,
          role: null,
          attendance_id: null,
          approver_id: null,
        };
        this.addUserDialog = false;
      }
      if (data === "update") {
        this.updateUserForm = {
          username: null,
          password: null,
          name: null,
          phone: null,
          address: null,
          town_id: null,
          role: null,
          attendance_id: null,
          approver_id: null,
        }
        this.updateUserDialog = false;
      }
    },
    // 修改用户
    updateUser(item) {
      this.updateUserForm = { ...item };
      this.updateUserDialog = true;
    },
    // 修改用户
    update(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            updateUser(this.updateUserForm).then((res) => {
              if(res.status === 0){
                this.$message.success('修改成功')
                this.getAccount();
                 this.updateUserDialog = false;
              }
            });
          } else {
            return false;
          }
        });
    },
    delUser(item) {
        console.log("删除用户", item);
        deleteUser(item).then(res=>{
          if(res.status === 0){
            this.$message.success(res.message)
            this.getAccount()
          }
        })
    },
    // 根据用户所属的区域更改审批组信息和考勤组信息
    getApprover(id) {
        idToApprover(id).then((res) => {
          if (res.status === 0) {
            this.approverData = res.data;
            console.log(this.approverData);
          }
        });
        
    },
    // 根据用户所属区域id获取考勤组信息
    getAttendance(id) {
        idToAttendance(id).then((res) => {
          if(res.status === 0){
              this.attendanceData = res.data
            }
        });
    },
    // 跳转用户考勤界面
    handlerRow(row){
      console.log(row);
      this.$router.push({
        path:`/userAttendance/${row.id}`
      })
    }
  },
  created() {
      this.getAccount();
  },
};
  </script>
      
  <style lang="less" scoped>
  .app-container {
    width: 100%;
    height: 100%;
    padding: 0;
  }

  .search {
    display: flex;
    margin: 10px;
  }

  .search {
    .el-input {
      width: 70%;
    }
  }

  .block {
    margin-top: 10px;
    float: right;
  }

  .app-container {
    .header {
      .searchParams {
        text-align: left !important;
        padding: 0 !important;
        line-height: 30px !important;
      }
    }
  }

  ::v-deep .el-dialog {
    margin: 0 auto 5vh !important;
  }
  </style>